var app = getApp();
import { CategoryModel } from '../../models/CategoryModel.js'
let Adress = new CategoryModel()
let locat = require('../../utils/Location.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //定义地址数据
    addressData: {
      user: '',
      phone: '',
      region: [],
      location:[],
      detail: '',
      tag: [
        {
          isSelect: true,
          title: '家',
          id:'0'
        },
        {
          isSelect: false,
          title: '公司',
          id:'1'
        },
        {
          isSelect: false,
          title: '学校',
          id:'2'
        },
        {
          isSelect: false,
          title: '其他',
          id:'3'
        }
      ],
      //0: 非默认，1: 默认
      default: 0,
    },
    indicatorDots: false,
    //地址id
    id: '',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var that = this
    //截取地址id
    if(options.result) {
      let result = JSON.parse(options.result)
      var id = result.id;
        that.setData({
          id: id,
          ids:result.ids
        })
      wx.setNavigationBarTitle({
        title: '编辑地址'
      })
      that.getAddressById();
    }else{
      that.setData({
        ids:options._id
      })
    }
  },
  //打开定位地图
  choseLocation: function(res) {
    console.log(res)
    var that = this;
    let data = that.data.addressData.location
    let latitude = res.latitude
    let longitude = res.longitude
    if(data){
      latitude = data[0]
      longitude = data[1]
    }
    wx.chooseLocation({
      latitude,
      longitude,
      success: function(e){
        console.log(e);
        let filename = e.name;
        let location = [e.latitude, e.longitude]

        let result = null;
        if (result == null || filename=="") {
          locat.getGpsLocation(e.latitude, e.longitude).then((res) => {
            console.log('反推了', res);
            if (res) {
              let s_region = [res.province, res.city, res.district]
  
              filename || (filename = res.street);
              that.setData({
                'addressData.region':s_region,
                'addressData.detail':filename,
                'addressData.location':location
              })
              console.log(that.data.addressData.region)
            }
          });
        }

      },
      fail: function (error) {
        if (error.errMsg =='chooseLocation:fail auth deny') {
          console.log('无权限')
          wx.getSetting({
            success(res) {
              if (!res.authSetting["scope.userLocation"]) { //未授权走这一步
                wx.showModal({
                  title: '温馨提示',
                  content: '检测到您没打开定位权限，是否去设置打开？',
                  showCancel: true,
                  cancelText: '取消',
                  cancelColor: '#000000',
                  confirmText: '确定',
                  confirmColor: '#3CC51F',
                  success: async(result) => {
                      if (result.confirm) {
                        wx.openSetting({
                          success: (res) => {

                           }
                        })
                      }else if(result.cancel) {
                      
                        return;
                      }
                  }
                });
              }
            }
          })
        }
      }
    })
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
  },
  //根据地址id获取地址数据
  getAddressById: function () {
    var that = this
    let address = wx.getStorageSync('address') //获取缓存中address信息
    
    console.log(address)
    let addressData = that.data.addressData
      //绑定数据
      var dataKey = ['user', 'phone', 'location', 'detail', 'default'];
      dataKey.forEach(v => {
        addressData[v] = address[v];
      })
      addressData.tag.map(function (value, index) {
        if(value.isSelect){ value.isSelect = false};
        if(value.id == address.tag) {value.isSelect = true};
        return;
      }); 
      addressData.region = [...address.region]
      if(address.default == 1){
        that.setData({
          indicatorDots: true,
        })
      }
      that.setData({
        addressData: addressData,
      })
      console.log(addressData)
  },
  // 修改联系人
  modifyUser: function (e) {
    console.log('e ==> ', e);
    this.data.addressData.user = e.detail.value;
    this.setData({
      addressData: this.data.addressData
    })
  },
  //修改手机号
  modifyPhone: function (e) {
    console.log('e ==> ', e);
    //验证手机号格式
    //\d: 表示 [0-9]
    // ^: 开头
    // $: 结尾
    var phoneReg = /^1[3456789]\d{9}$/
    //如果验证失败，返回false
    if (!phoneReg.test(e.detail.value)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none',
        duration: 2000
      })
      this.data.addressData.phone = ''
    } else {
      this.data.addressData.phone = e.detail.value;
    }

    this.setData({
      addressData: this.data.addressData
    })

  },
  //修改门牌号
  modifyDetail: function (e) {
    this.setData({
      'addressData.detail': e.detail.value
    })
  },
  //切换标签
  toggleTag: function (e) {
    console.log(e)
    this.toggleStatus(e, 'tag')
  },

  //切换状态
  toggleStatus: function (e, key) {
    //如果当前选中，则不做任何事情
    if (e.currentTarget.dataset.isSelect) {
      return;
    }
    //清除其他选中的，选中点击的
    for (var i = 0; i < this.data.addressData[key].length; i++) {
      if (this.data.addressData[key][i].isSelect) {
        this.data.addressData[key][i].isSelect = false;
        break;
      }
    }

    this.data.addressData[key][e.currentTarget.dataset.index].isSelect = true;

    this.setData({
      addressData: this.data.addressData
    })
  },
  //切换默认地址
  toggleDefault: function (e) {
    this.setData({
      indicatorDots:!this.data.indicatorDots,
      'addressData.default': this.data.indicatorDots ? 0 : 1,
    })
  },
    //保存
  save: function () {
    //用于保存在数据库中的地址数据
    var address = {};
    address.uid = '1';//uid  
    //构造数据验证表单是否存在空值
    var data = {
      user: {
        value: '',
        msg: '联系人不能为空'
      },
      phone: {
        value: '',
        msg: '手机号不能为空'
      },
      region: {
        value: '',
        msg: '请填写地址'
      },
      detail: {
        value: '',
        msg: '门牌号不能为空'
      }
    };
    console.log(this.data.addressData)
    let res = this.data.addressData
    for (var key in data) {
      if (res[key] == data[key].value) {
        wx.showToast({
          title: data[key].msg,
          icon: 'none',
          duration: 2000
        })
        return;
      }
      address[key] = res[key];
    }
    //获取性别、标签、默认地址
      for (var i = 0; i < res.tag.length; i++) {
        if (res.tag[i].isSelect) {
          address.tag = res.tag[i].id;
          break;
        }
      }
    address.location = res.location;  
    address.default = res.default;
    console.log('address ==> ', address);

    //如果地址id存在，则修改地址，否则新增地址
    if (this.data.id){
      if(address.default ==1){
        console.log('存在默认地址')
        if(this.data.id !== this.data.ids){
          let ids = {};
          ids._id = this.data.ids;
          ids.default = 0;
          console.log('id不匹配')
          Adress.updatedShopcart(ids, data => {
            console.log(data)
          })
        }
      }

      let obj = [this.data.id,address]
      console.log('address ==> ', obj);
      Adress.updatedAddress(obj, data => {
        console.log(data)
        if(data.errMsg == "cloud.callFunction:ok"){
            wx.showToast({
              title: '更新成功',
              icon: 'success'
            })
        }
        this.handleClick()
      })
      console.log('修改')
    }else{  
      if(address.default ==1){
        let ids = {};
        ids._id = this.data.ids;
        ids.default = 0;
        Adress.updatedShopcart(ids, data => {
          console.log(data)
        })
      }
      wx.showLoading({
        title: '加载中...'
      })
      Adress.addAddress(address, data => {
        console.log(data)
        if(data.errMsg == "cloud.callFunction:ok"){
            wx.showToast({
              title: '加入成功',
              icon: 'success'
            })
        }
        this.handleClick()
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  handleClick(){
    let pages = getCurrentPages();   //获取小程序页面栈
    let beforePage = pages[pages.length -2];  //获取上个页面的实例对象
    // beforePage.setData({      //直接修改上个页面的数据（可通过这种方式直接传递参数）
    //   txt:'修改数据了'
    // })
    beforePage.go_update();   //触发上个页面自定义的go_update方法
    wx.navigateBack({         //返回上一页  
      delta:1
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})